package com.eastwit.api.service.funing.impl;

import com.eastwit.api.config.datasource.DataSourceContextHolder;
import com.eastwit.api.mapper.InfoGetDao;
import com.eastwit.api.service.funing.InfoGetService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: cyy
 **/
@Slf4j
@Service
public class InfoGetServiceImpl implements InfoGetService {

    @Value("${fn.civilcode}")
    private String civilcode;

    private final static String DEFAULT = "default";
    private final static String MASTER = "master";

    @Autowired
    private InfoGetDao infoGetDao;

    @Override
    public void startGetInfo() {
        DataSourceContextHolder.setDBType(MASTER);
        boolean flag = true;
        int curPage = 1;
        List<String> result = new ArrayList<>();
        try {
            while (flag) {
                //分页日志结果
                PageHelper.startPage(curPage, 3000, false);
                List<String> deviceInfo = infoGetDao.getDeviceInfo(civilcode);
                //没有结果 结束while
                flag = CollectionUtils.isNotEmpty(deviceInfo);
                if (!flag) {
                    break;
                }
                curPage++;
                result.addAll(deviceInfo);
            }
            //写入本级数据库
            DataSourceContextHolder.setDBType(DEFAULT);
            if (CollectionUtils.isNotEmpty(result)){
                //清空历史数据
                infoGetDao.truncateTable("ao_pro_sharethan");
                infoGetDao.insetInfo(result);
            }
        } catch (Exception e) {
            log.info("get info failed ,please check your code" + e.getMessage() +  "========cause" + e.getCause());
            e.printStackTrace();
        }
    }
}
